package com.ia.aistream.manager.operating.util.tools;

import com.ia.aistream.common.utils.UUID;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 操作Doc文档的工具类
 * @author XiaoYu
 */
public class DocToolUtil {

    /***
     * 实现Word文件转HTML文件
     * @param fileName
     * @return
     */
    public static String docToHtml(String fileName){

        String ext = fileName.substring(fileName.lastIndexOf("."));
        String newFile = fileName.replace(ext, ".html");
        Document document = new Document();
        document.loadFromFile(fileName);

        document.saveToFile(newFile, FileFormat.Html);
        return newFile;
    }

    /***
     * 判断图片是否为公式
     * @param docPicture
     * @return
     */
    public static boolean isFormulaImg(DocPicture docPicture){
        float height = docPicture.getHeight();
        if(height>40){
            return false;
        }
        return true;
    }

    /***
     * 处理特殊含义的字符
     * @param content
     * @return
     */
    public static String handleSpecialData(String content, TextRange range){
        // 处理大于号和小于号
        content = content.replace("<", "&lt;");
        content = content.replace(">", "&gt;");
        content = content.replace("\t", "&ensp;&ensp;");
        content = content.replace(" ", "&ensp;");

        // 判断是否为角标
        if (range.getCharacterFormat().getSubSuperScript().toString().equals("Sub_Script")){
            content = "<sub style='font-size: 1px'>" + content +"</sub>";
        }else if(range.getCharacterFormat().getSubSuperScript().toString().equals("Super_Script")){
            content = "<sup style='font-size: 1px'>" + content +"</sup>";
        }
        return content;
    }

    /***
     * 将图片下载到本地
     * @param docPicture  图片对象
     * @param path  新文件保存地址
     * @throws IOException
     */
    public static void downloadImages(DocPicture docPicture, String path)  {
        FileOutputStream fis = null;
        try{
            byte[] bytes = docPicture.getImageBytes();
            File file = new File(path);
            fis = new FileOutputStream(file);
            fis.write(bytes);
        }catch (IOException e){
            throw new RuntimeException("图片保存失败");
        }finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /****
     * 获取UUID
     * @return
     */
    public static String getUUID(){
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static void main(String[] args) {
        System.out.println(getUUID());;
    }
}
